import React, { useState, useMemo, useEffect } from 'react';
import { Form, Input, Select, Button, Radio, Space, DatePicker, TreeSelect, Spin } from 'antd';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { dictData } from '@/services/prefiling/onlineCollecting';
import { useModel } from 'umi';

const { RangePicker } = DatePicker;

interface QueryField {
  name: string;
  label: string;
  syllableType?: string;
  dictCode?: string;
  options?: Array<{label: string; value: any}>;
  defaultValue?: string;
  code?: string;
  fieldPrompt?: string;
}

interface DynamicQueryFormProps {
  type: 'file' | 'roll' | 'fileList' | 'unFileList';
  fields: QueryField[];
  initialValues?: Record<string, any>;
  onSearch: (values: any) => void;
  onReset: () => void;
}

interface DictionaryData {
  [dictCode: string]: Array<{value: string; label: string}>;
}

interface DictionaryItem {
  value: string;
  label: string;
}

interface TreeDataItem {
  value: string;
  title: string;
  children?: TreeDataItem[];
}

const DynamicQueryForm: React.FC<DynamicQueryFormProps> = ({
  type,
  fields,
  initialValues,
  onSearch,
  onReset
}) => {
    const [form] = Form.useForm();
    const [expanded, setExpanded] = useState(false);
    const [itemsPerRow, setItemsPerRow] = useState(3);
    const [loading, setLoading] = useState(false);
    const [sessionType, setSessionType] = useState<Array<{value: string; label: string}>>([]);
    const [dictionaryData, setDictionaryData] = useState<DictionaryData>({});
    const [fieldOptions, setFieldOptions] = useState<Record<string, DictionaryItem[]>>({});
    const [fieldTreeData, setFieldTreeData] = useState<Record<string, TreeDataItem[]>>({});
    const [fieldLoading, setFieldLoading] = useState<Record<string, boolean>>({});
    const containerRef = React.useRef<HTMLDivElement>(null);
    const { initialState } = useModel('@@initialState');
    const { currentUser } = initialState || {};

  // 计算每行能显示的查询条件数量
  useEffect(() => {
    const calculateItemsPerRow = () => {
      if (!containerRef.current) return;
      const containerWidth = containerRef.current.offsetWidth;
      const availableWidth = containerWidth - 170; // 减去右侧按钮区域宽度
      const calculatedItems = Math.max(1, Math.floor(availableWidth / 280));
      setItemsPerRow(calculatedItems);
    };

    calculateItemsPerRow();
    window.addEventListener('resize', calculateItemsPerRow);
    return () => window.removeEventListener('resize', calculateItemsPerRow);
  }, []);

  // 获取session-type数据
  useEffect(() => {
    const fetchFieldData = async () => {
      const fieldsToLoad = fields.filter(field => {
        const syllableType = parseInt(field.syllableType || '1');
        return [2, 10, 11, 3, 13, 14].includes(syllableType) && field.dictCode;
      });

      for (const field of fieldsToLoad) {
        const syllableType = parseInt(field.syllableType || '1');
        try {
          setFieldLoading(prev => ({ ...prev, [field.name]: true }));
          const res = await dictData({ dictType: field.dictCode! });
          
          if ([2, 10, 11].includes(syllableType)) {
            setFieldOptions(prev => ({ ...prev, [field.name]: res || [] }));
          } else if ([13, 14].includes(syllableType)) {
            setFieldTreeData(prev => ({ ...prev, [field.name]: res || [] }));
          }
        } catch (error) {
          console.error('Failed to load dictionary data:', error);
        } finally {
          setFieldLoading(prev => ({ ...prev, [field.name]: false }));
        }
      }
    };

    fetchFieldData();
  }, [fields]);


  const visibleFields = expanded ? fields : fields.slice(0, itemsPerRow);

  useEffect(() => {
    if (initialValues) {
      if(JSON.stringify(initialValues) === '{}'){
        form.resetFields();
      }
      form.setFieldsValue({ searchType: '2', ...initialValues });
    }
  }, [initialValues]);

  const toggleExpand = () => {
    setExpanded(!expanded);
  };

  const parseDefaultValue = (defaultValue: string): string => {
    const defaultData = sessionType.filter(item => item.value === defaultValue);
    let value = defaultValue;
    if (defaultData.length) {
      switch (defaultValue) {
        case "NOW_YEAR":
          value = getNowDate("year");
          break;
        case "NOW_MONTH":
          value = getNowDate("month");
          break;
        case "NOW_DATE":
          value = getNowDate();
          break;
        case "NOW_DATETIME":
          value = getNowDate("datetime");
          break;
        default:
          value = currentUser?.[defaultValue] || "";
          break;
      }
    }
    return value;
  };

  const getNowDate = (type?: string): string => {
    const now = new Date();
    switch (type) {
      case "year":
        return now.getFullYear().toString();
      case "month":
        return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
      case "datetime":
        return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
      default:
        return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
    }
  };

  const renderFormItem = (field: QueryField) => {
    const fieldPrompt = field.fieldPrompt || `请输入${field.label}`;
    const syllableType = field.syllableType || '1';
    const options = fieldOptions[field.name] || [];
    const treeData = fieldTreeData[field.name] || [];
    const itemLoading = fieldLoading[field.name] || false;

    if (itemLoading) {
      return <Spin />;
    }

    switch (syllableType) {
      case '1': //文本框
        return (
          <Input 
            placeholder={fieldPrompt}
            className={`table_input ${field.code}`}
            defaultValue={parseDefaultValue(field.defaultValue || '')}
            style={{ width: 180 }}
          />
        );
        
      case '2': //数据字典下拉框
      case '10'://单选框
      case '11'://多选框
        const isMultiple = syllableType === '11';
        
        if (field.code === "nativePlace") {
          return (
            <div style={{ display: 'flex', width: 360 }}>
              <Select
                className="dictSelect province"
                placeholder={fieldPrompt}
                style={{ width: 175 }}
                options={options}
              />
              <Select
                name={field.code}
                className={field.code}
                style={{ width: 175, marginLeft: 5 }}
                options={[]}
              />
            </div>
          );
        }
        
        return (
          <Select
            name={field.code}
            className={`dictSelect ${field.code}`}
            placeholder={fieldPrompt}
            mode={isMultiple ? 'multiple' : undefined}
            style={{ width: 180 }}
            options={options.map(item => ({
              value: field.code === "taskStatus" ? item.value : item.label,
              label: item.label
            }))}
            defaultValue={
              field.defaultValue && options.find(opt => 
                opt.label === field.defaultValue || opt.value === field.defaultValue
              )?.label
            }
          />
        );
        
      case '3': //接口型下拉框
        return (
          <Select
            name={field.code}
            placeholder={fieldPrompt}
            className={`dynamicDictSelect ${field.code}`}
            style={{ width: 180 }}
            loading={itemLoading}
            options={options}
            defaultValue={field.defaultValue}
          />
        );
        
      case '4': //日期
        return (
          <DatePicker
            name={field.code}
            placeholder={fieldPrompt}
            className={`table_input time-input ${field.code}`}
            format="YYYY-MM-DD"
            defaultValue={parseDefaultValue(field.defaultValue || '')}
            style={{ width: 180 }}
          />
        );
        
      case '5'://时间框
        return (
          <DatePicker
            name={field.code}
            placeholder={fieldPrompt}
            className={`table_input time-input ${field.code}`}
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            defaultValue={parseDefaultValue(field.defaultValue || '')}
            style={{ width: 180 }}
          />
        );
        
      case '6': //年月
        return (
          <DatePicker
            name={field.code}
            placeholder={fieldPrompt}
            className={`table_input time-input ${field.code}`}
            picker="month"
            format="YYYY-MM"
            defaultValue={parseDefaultValue(field.defaultValue || '')}
            style={{ width: 180 }}
          />
        );
        
      case '7'://年
        return (
          <DatePicker
            name={field.code}
            placeholder={fieldPrompt}
            className={`table_input time-input ${field.code}`}
            picker="year"
            format="YYYY"
            defaultValue={parseDefaultValue(field.defaultValue || '')}
            style={{ width: 180 }}
          />
        );
        
      case '12'://时间段
        const [startDate, endDate] = field.defaultValue ? field.defaultValue.split("~") : ['', ''];
        
        return (
          <div style={{ display: 'flex', width: 360 }}>
            <DatePicker
              name={`start${field.code}`}
              placeholder={fieldPrompt}
              className={`table_input startTime start${field.code}`}
              defaultValue={startDate}
              style={{ width: 175 }}
            />
            <span style={{ width: 10, textAlign: 'center' }}>-</span>
            <DatePicker
              name={`end${field.code}`}
              placeholder={fieldPrompt}
              className={`table_input endTime end${field.code}`}
              defaultValue={endDate}
              style={{ width: 175 }}
            />
          </div>
        );
        
      case '13': //树形选择框
      case '14': //多选树形选择框
        const [txt] = field.defaultValue ? field.defaultValue.split("?") : [''];
        const isCheckable = field.syllableType === '14';
        
        return (
          <TreeSelect
            name={field.code}
            className={`treeDynamicDictSelect ${field.code}`}
            treeCheckable={isCheckable}
            placeholder={fieldPrompt}
            defaultValue={txt}
            style={{ width: 180 }}
            treeData={treeData}
            fieldNames={{ label: 'label', value: 'value', children: 'children' }}
          />
        );
        
      default:
        return (
          <Input 
            placeholder={fieldPrompt}
            className={`table_input ${field.code}`}
            defaultValue={field.defaultValue}
            style={{ width: 180 }}
          />
        );
    }
  };

  if (fields.length === 0) return null;

  return (
    <div 
      ref={containerRef}
      style={{ 
        marginBottom: 16,
        position: 'relative'
      }}
    >
      <Form
        form={form}
        layout="inline"
        onFinish={onSearch}
        initialValues={{ searchType: '2', ...initialValues }}
        style={{ 
          padding: 16,
          background: '#fafafa',
          borderRadius: 4,
          display: 'flex',
          flexWrap: 'wrap',
          alignItems: 'flex-start'
        }}
      >
        {/* 查询条件区域 */}
        <div style={{
          display: 'flex',
          flexWrap: 'wrap',
          width: 'calc(100% - 170px)',
          gap: '16px 0',
          alignItems: 'flex-start'
        }}>
          {visibleFields.map((field) => (
            <div key={field.name} style={{ 
              width: 280, 
              marginRight: 16,
              display: 'flex',
              alignItems: 'center'
            }}>
              <Form.Item 
                name={field.name} 
                label={field.label}
                style={{ 
                  marginBottom: 0, 
                  display: 'flex',
                  alignItems: 'center'
                }}
                labelCol={{ style: { 
                  width: 80, 
                  textAlign: 'right', 
                  marginRight: 8,
                  flexShrink: 0
                } }}
              >
                {renderFormItem(field)}
              </Form.Item>
            </div>
          ))}
          
          {/* 单选条件 */}
          {visibleFields.length > 0 && (
            <div style={{ 
              width: 280, 
              marginRight: 16,
              display: 'flex',
              alignItems: 'center'
            }}>
              <Form.Item 
                name="searchType" 
                label=""
                style={{ 
                  marginBottom: 0,
                  display: 'flex',
                  alignItems: 'center'
                }}
                labelCol={{ style: { 
                  width: 80, 
                  textAlign: 'right', 
                  marginRight: 8,
                  flexShrink: 0
                } }}
              >
                <Radio.Group>
                  <Radio value="1">精准</Radio>
                  <Radio value="2">模糊</Radio>
                </Radio.Group>
              </Form.Item>
            </div>
          )}
        </div>
        <div style={{ 
          width: 170,
          display: 'flex',
          justifyContent: 'flex-end',
          alignItems: 'flex-start',
          marginTop: 0
        }}>
          <Space align="start">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={() => { form.resetFields(); onReset(); }}>
              重置
            </Button>
            {fields.length > itemsPerRow && (
              <Button 
                type="text" 
                icon={expanded ? <UpOutlined /> : <DownOutlined />}
                onClick={toggleExpand}
              />
            )}
          </Space>
        </div>
      </Form>
    </div>
  );
};

export default DynamicQueryForm;